(function ($) {
    $.fn.yqSvrAdNsq = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqSvrAdNsq.methods[opts](this, param);
        }

        var $this = this;
        var opt = $.extend({}, $.fn.yqSvrAdNsq.defaults, opts);

        if ($this.data("yqtype") == "yqSvrAdNsq") {
            var $uniqueID = $this.attr("ID");
            destroy($this);
            $this = $("#" + $uniqueID);
        }
        else {
            var $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined) {
                $uniqueID = $.getUniqueID();
                $this.attr("ID", $uniqueID);
            }
        }

        if (opt.width === undefined && $this.width() > 0) {
            opt.width = $this.width();
        }
        else if (typeof opt.width != "undefined") {
            $this.width(opt.width);
        }
        if (opt.height === undefined && $this.height() > 0) {
            opt.height = $this.height();
        } else if (typeof opt.height != "undefined") {
            $this.height(opt.height);
        }

        opt.serviceStatus = "inactive";

        //变量信息
        $this.data("svradnsq_opt", opt);
        $this.data("yqtype", "yqSvrAdNsq");

        init_ui($this);
    };

    $.fn.yqSvrAdNsq.defaults = {
        ajaxUrl: "/_svradmin.html",
        isEdit: true,
        afterBindingTitle: function () { },   //标题绑定后
    };

    $.fn.yqSvrAdNsq.methods = {
        options: function (jq) {
            return options(jq);
        },
        destroy: function (jq) {
            //destroy($(jq[0]));
        },
        resize: function (jq, params) {
            resize(jq, params);
        },

        isEdit: function (jq, tf) {
            //isEdit($(jq[0]), tf);
        }
    };

    function options($object) {
        return $object.data("svradnsq_opt");
    }

    function isEdit($object, tf) {
        var opt = options($object);
        if (tf === undefined) {
            tf = opt.isEdit;
        } else {
            opt.isEdit = tf;
        }

        updateButtonStates($object);
    }

    function destroy($object) {
    }

    function resize($object, params) {
        var opt = options($object);
        if (!(params === undefined)) {
            if (!(params.width === undefined)) {
                opt.width = params.width;
            }
            if (!(params.height === undefined)) {
                opt.height = params.height;
            }
        }

        $object.width(opt.width);
        $object.height(opt.height);

        var w_ = opt.width;
        var h_ = opt.height - 42;

        opt.$div_tabs.tabs("resize", {
            width: w_,
            height: h_
        });

        var _css = {
            overflow: "auto",
            width: w_,
            height: h_ - 36
        };
        opt.$div_tabs_streams.css(_css);
        opt.$div_tabs_nodes.css(_css);
        opt.$div_tabs_counter.css(_css);
        opt.$div_tabs_lookup.css(_css);
    }

    async function page_load($object) {
        var opt = options($object);

        resize($object);

        await checkStatus($object);

        opt.$div_tabs.tabs("options").onSelect = function (title, index) {
            tab_select($object, index);
        };

        var tab = opt.$div_tabs.tabs('getSelected');
        var index = opt.$div_tabs.tabs('getTabIndex', tab);
        tab_select($object, index);

        opt.afterBindingTitle.call($object);
    }

    function init_ui($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("ID");
        var h_ = `
<table style="width: 100%;">
    <tr>
        <td style="padding:4px 10px 4px 4px;width:100px;white-space:nowrap;">
            <input class="btn_email"/>
            <a class="send_email">发送邮件</a>
        </td>
        <td style="padding:4px 4px 4px 10px;width:100px;white-space:nowrap;">    
            <input class="btn_sms"/>
            <a class="send_sms">发送短信</a>
        </td>
        <td style="padding:4px 10px 4px 4px;text-align:right;">
            <span>当前状态：</span>
            <span class="txt_status"></span>
        </td>
    </tr>
</table>
<div class="div_tabs"">
</div>  
        `;

        $object.html(h_);

        opt.$btn_email = $object.find(".btn_email");
        opt.$send_email = $object.find(".send_email");
        opt.$btn_sms = $object.find(".btn_sms");
        opt.$send_sms = $object.find(".send_sms");

        opt.$txt_status = $object.find(".txt_status");

        opt.$div_tabs = $object.find(".div_tabs");

        opt.$btn_email.switchbutton({
            width: 115,
            height: 35,
            handleWidth: 70,
            checked: false,
            onText: '开启',
            offText: '关闭',
            handleText: '<i class="fa fa-envelope"> email</i>',
            disabled: true,
        });

        opt.$send_email.linkbutton({
            width: 70,
            height: 35,
            text: '测试',
            iconCls: 'fa fa-paper-plane',
            disabled: true,
            onClick: function () {
                send_email($object);
            }
        });

        opt.$btn_sms.switchbutton({
            width: 115,
            height: 35,
            handleWidth: 70,
            checked: false,
            onText: '开启',
            offText: '关闭',
            handleText: '<i class="fa fa-commenting"> sms</i>',
            disabled: true,
        });

        opt.$send_sms.linkbutton({
            width: 70,
            height: 35,
            text: '测试',
            iconCls: 'fa fa-paper-plane',
            disabled: true,
            onClick: function () {
                send_sms($object);
            }
        });

        opt.$div_tabs.tabs({
            plain: true,
            fit: true,
            border: false,
            resize: true,
        });

        // 初始化所有tabs
        var tabsToAdd = [
            { id: "streams", title: "Streams", content: "Streams" },
            { id: "nodes", title: "Nodes", content: "Nodes" },
            { id: "counter", title: "Counter", content: "Counter" },
            { id: "lookup", title: "Lookup", content: "Lookup" }
        ];

        tabsToAdd.forEach(function (tab, index) {
            opt.$div_tabs.tabs("add", {
                title: tab.title,
                content: '<div class="tabs-' + tab.id + '">' + tab.content + '</div>',
                closable: false,
                selected: index === 0
            });
        });

        // 获取所有tab的panel引用
        opt.$div_tabs_streams = $object.find(".tabs-streams");
        opt.$div_tabs_nodes = $object.find(".tabs-nodes");
        opt.$div_tabs_counter = $object.find(".tabs-counter");
        opt.$div_tabs_lookup = $object.find(".tabs-lookup");
        page_load($object);
    }

    // 检查服务状态
    async function checkStatus($object) {
        var opt = options($object);

        try {
            const response = await fetch(opt.ajaxUrl + `?action=nsq:ping`);
            const data = await response.json();
            console.log("status", data);
            if (data.error == 0) {
                opt._email = data.email;
                opt._sms = data.sms;
                updateStatusDisplay($object, data.status);
            } else {
                $.yqMessager("error", data.info);
            }
        } catch (error) {
            $.yqMessager("error", '获取状态失败：' + error.message);
        }
    }

    function updateStatusDisplay($object, status) {
        var opt = options($object);

        opt.$txt_status.text(status === 'active' ? '运行中' : '已停止');
        opt.$txt_status.attr("class", 'status ' + status);
        opt.serviceStatus = status;
        updateButtonStates($object);
    }

    // 更新按钮状态
    function updateButtonStates($object) {
        var opt = options($object);

        var serviceStatus = opt.serviceStatus;

        if (serviceStatus === undefined || (!opt.isEdit)) {
            opt.$btn_email.switchbutton("disable");
            opt.$send_email.linkbutton("disable");
            opt.$btn_sms.switchbutton("disable");
            opt.$send_sms.linkbutton("disable");
            return;
        }

        if (serviceStatus === 'active') {
            opt.$btn_email.switchbutton("enable");
            opt.$btn_email.switchbutton(opt._email ? "check" : "uncheck");
            opt.$btn_email.switchbutton("options").onChange = function (checked) {
                console.log("checked", checked);
                if (checked) {
                    startService($object, 'email');
                } else {
                    stopService($object, 'email');
                }
            };
            opt.$send_email.linkbutton("enable");

            opt.$btn_sms.switchbutton("enable");
            opt.$btn_sms.switchbutton(opt._sms ? "check" : "uncheck");
            opt.$btn_sms.switchbutton("options").onChange = function (checked) {
                console.log("checked", checked);
                if (checked) {
                    startService($object, 'sms');
                } else {
                    stopService($object, 'sms');
                }
            };
            opt.$send_sms.linkbutton("enable")
        }
        else {
            opt.$btn_email.switchbutton("uncheck");
            opt.$btn_email.switchbutton("disable");
            opt.$send_email.linkbutton("disable");

            opt.$btn_sms.switchbutton("uncheck");
            opt.$btn_sms.switchbutton("disable");
            opt.$send_sms.linkbutton("disable");
        }
    }

    // 服务操作函数
    function startService($object, name) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "nsq:start");
        formData.append("name", name);
        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            if (res.error == 0) {
                opt["_" + name] = true;
                $.yqMessager("success", name + "服务已启动");
            } else {
                opt["_" + name] = false;
                $.yqMessager("error", res.info);
            }

            updateStatusDisplay($object, 'active');
        })
    }

    function stopService($object, name) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "nsq:stop");
        formData.append("name", name);
        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            opt["_" + name] = false;
            if (res.error == 0) {
                $.yqMessager("success", name + "服务已关闭");
            } else {
                $.yqMessager("error", res.info);
            }

            updateStatusDisplay($object, 'active');
        })
    }

    function send_email($object) {
        var opt = options($object);
        var prevent_e = $.getPreventDefault(opt.$send_email);
        var _opt = {
            prevent_e: prevent_e,
            mdiinfo: $.yqGetWindParams(),
            title: "发送邮件",
            width: 450,
            height: 342,
            buttons: [],
            closeBtn: true,
            closeBtnText: "关闭",
            onOpen: function ($body) {
                $body.css({
                    overflow: "hidden"
                });
                var $h_ = $(`
<table style="padding: 10px 0 0 15px;">
    <tr>
        <td style="padding: 0px 5px 8px 5px;">
            <label>收件人</label>
        </td>
        <td style="padding: 0 5px 8px 0;">
            <input class="email_to" style="width:350px;" title="请输入收件人邮箱，多个邮箱用逗号分隔"/>
        </td>
    <tr>
    <tr style="margin-bottom: 10px;">
        <td style="padding: 0 5px 8px 0;">
            <label>主题</label>
        </td>
        <td style="padding: 0px 5px 8px 0;">
            <input class="email_subject" style="width:350px;" title="请输入邮件主题"/>
        </td>
    <tr>
     <tr>
        <td style="padding: 0 5px 0 0;">
            <label>内容</label>
        </td>
        <td style="padding: 0px 5px 0 0;">
            <textarea class="email_body" style="width:350px;height:165px;"/>
      </td>
    <tr>
</table>`);
                $body.html($h_);

                // 从本地缓存获取数据
                var cached_to = localStorage.getItem('nsq:email_to') || '';
                var cached_subject = localStorage.getItem('nsq:email_subject') || '';
                var cached_body = localStorage.getItem('nsq:email_body') || '';

                $h_.find(".email_to").textbox({
                    required: true,
                    validType: 'email',
                    prompt: '请输入收件人邮箱，多个邮箱用逗号分隔',
                    value: cached_to
                });
                $h_.find(".email_subject").textbox({
                    required: true,
                    validType: 'length[1,100]',
                    prompt: '请输入邮件主题',
                    value: cached_subject
                });
                $h_.find(".email_body").textbox({
                    multiline: true,
                    required: true,
                    validType: 'length[1,100]',
                    prompt: '请输入邮件内容',
                    value: cached_body
                });
            },
            buttons: [{
                id: "btn_send",
                text: "发送",
                onClick: function ($body) {
                    var $email_to = $body.find(".email_to");
                    var $email_subject = $body.find(".email_subject");
                    var $email_body = $body.find(".email_body");

                    if (!$email_to.textbox("isValid") || !$email_subject.textbox("isValid") || !$email_body.textbox("isValid")) {
                        $.yqMessager("error", "请检查输入的内容是否正确?");
                    } else {
                        var e_to = $email_to.textbox("getValue");
                        var e_subject = $email_subject.textbox("getValue");
                        var e_body = $email_body.textbox("getValue");

                        // 保存到本地缓存
                        localStorage.setItem('nsq:email_to', e_to);
                        localStorage.setItem('nsq:email_subject', e_subject);
                        localStorage.setItem('nsq:email_body', e_body);

                        $.yqDialog_fun.call(this, "close");

                        var formData = new FormData();
                        formData.append("action", "nsq:sendemail");
                        formData.append("to", JSON.stringify(e_to.split(",")));
                        formData.append("subject", e_subject);
                        formData.append("body", e_body);
                        ajaxLoad(opt, formData, function (res) {
                            console.log(res);
                            if (res.error == 0) {
                                $.yqMessager("success", "邮件发送成功");
                            } else {
                                $.yqMessager("error", res.info);
                            }
                        });

                    }
                }
            }],
        };
        if (window.top == window.self) {
            $.yqDialog(_opt);
        }
        else {
            window.top.$.yqDialog(_opt);
        }
    }

    function send_sms($object) {
        var opt = options($object);
        var prevent_e = $.getPreventDefault(opt.$send_sms);
        var _opt = {
            prevent_e: prevent_e,
            mdiinfo: $.yqGetWindParams(),
            title: "发送短信",
            width: 420,
            height: 340,
            closeBtn: true,
            closeBtnText: "关闭",
            onOpen: function ($body) {
                $body.css({
                    overflow: "hidden"
                });
                var $h_ = $(`
<table style="padding: 10px 0 0 15px;">
    <tr>
        <td style="padding: 0px 5px 8px 5px;">
            <label>provider</label>
        </td>
        <td style="padding: 0 5px 8px 0;">
            <input class="provider" style="width:150px;"/>
        </td>
    <tr>
    <tr>
        <td style="padding: 0px 5px 8px 5px;">
            <label>phone numbers</label>
        </td>
        <td style="padding: 0 5px 8px 0;">
            <input class="phone_to" style="width:150px;"/>
        </td>
    <tr>
    <tr>
        <td style="padding: 0px 5px 8px 5px;">
            <label>template code</label>
        </td>
        <td style="padding: 0 5px 8px 0;">
            <input class="template_code" style="width:150px;"/>
        </td>
    <tr>
    <tr>
        <td style="padding: 0px 5px 8px 5px;">
            <label>template param</label>
        </td>
        <td style="padding: 0 5px 8px 0;">
            <div class="template_param" style="width:250px;height:120px">
        </td>
    <tr>
</table>`);
                $body.html($h_);

                // 从本地缓存获取数据
                var provider = localStorage.getItem('nsq:provider') || 'aliyun';
                var phone_to = localStorage.getItem('nsq:phone_to') || '';
                var template_code = localStorage.getItem('nsq:template_code') || 'SMS_126315172';
                var template_param = localStorage.getItem('nsq:template_param') || '{"code":"123456"}';
                template_param = JSON.parse(template_param);

                $h_.find(".provider").combobox({
                    value: provider,
                    editable: false,
                    panelHeight: 'auto',
                    valueField: 'id',
                    textField: 'text',
                    data: [{
                        id: 'aliyun',
                        text: '阿里云'
                    }, {
                        id: 'tencent',
                        text: '腾讯云'
                    }]
                });

                $h_.find(".phone_to").textbox({
                    required: true,
                    validType: 'phone',
                    prompt: '请输入手机号，多手机号用逗号[,]分隔',
                    value: phone_to
                });
                $h_.find(".template_code").textbox({
                    required: true,
                    prompt: '请输入短信模板code',
                    value: template_code
                });
                $body.data("template_param", $h_.find(".template_param").yqCodeEdit({
                    types: ["json"],
                    type: "json",
                    goDocEnd: false,
                    value: JSON.stringify(template_param, null, 3),
                }));
            },
            buttons: [{
                text: "发送",
                onClick: function ($body) {
                    var provider = $body.find(".provider").combobox("getValue");
                    var phone_to = $body.find(".phone_to").textbox("getValue");
                    var template_code = $body.find(".template_code").textbox("getValue");
                    var template_param = $body.data("template_param").yqCodeEdit("getValue");
                    try {
                        template_param = JSON.parse(template_param);
                    } catch (e) {
                        $.yqMessager("error", "请检查输入的内容是否正确?" + e.message);
                        return;
                    }

                    console.log("template_param", template_param);

                    if (!phone_to || !template_code) {
                        $.yqMessager("error", "请检查输入的内容是否正确?");
                        return;
                    }

                    $.yqDialog_fun.call(this, "close");

                    // 保存到本地缓存
                    localStorage.setItem('nsq:provider', provider);
                    localStorage.setItem('nsq:phone_to', phone_to);
                    localStorage.setItem('nsq:template_code', template_code);
                    localStorage.setItem('nsq:template_param', JSON.stringify(template_param));

                    var formData = new FormData();
                    formData.append("action", "nsq:sendsms");
                    formData.append("provider", provider);
                    formData.append("phone_numbers", JSON.stringify(phone_to.split(',')));
                    formData.append("template_code", template_code);
                    formData.append("template_param", JSON.stringify(template_param));

                    ajaxLoad(opt, formData, function (res) {
                        console.log(res);
                        if (res.error == 0) {
                            $.yqMessager("success", "短信发送成功");
                        } else {
                            $.yqMessager("error", res.info);
                        }
                    });
                }
            }],
        };
        if (window.top == window.self) {
            $.yqDialog(_opt);
        } else {
            window.top.$.yqDialog(_opt);
        }
    }

    function tab_select($object, tab_index) {
        var opt = options($object);

        switch (tab_index) {
            case 0:
                dip_streams(opt);
                break;
            case 1:
                dip_nodes(opt);
                break;
            case 2:
                opt.$div_tabs_counter.html("Counter" + Date.now());

                break;
            case 3:
                dip_lookup(opt);

                break;
        }
    }

    function dip_streams(opt) {
        //opt.$div_tabs_streams.html("Streams" + Date.now());
        opt.$div_tabs_streams.empty();

        opt.$div_tabs_streams_div = $('<div></div>');

        var formData = new FormData();
        formData.append("action", "nsq:topics");

        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            if (res.error == 0) {
                opt.$div_tabs_streams.append("<h2>Topics</h2>");
                var $ul = $("<ul></ul>");
                for (var i = 0; i < res.topics.length; i++) {
                    var topic = res.topics[i].topic;
                    var $li = $('<li><a href="javascript:void(0);">' + topic + '</a></li>');
                    $ul.append($li);
                    $li.find("a").data("objdata", {
                        topic: topic,
                        $div: opt.$div_tabs_streams_div
                    });
                    $li.find("a").bind("click", function () {
                        nsq_lookup(opt, $(this));
                    })
                }
                opt.$div_tabs_streams.append($ul);

                opt.$div_tabs_streams.append(opt.$div_tabs_streams_div);
            } else {
                opt.$div_tabs_streams.html("error:" + res.info);
                $.yqMessager("error", res.info);
            }
        });
    }

    function dip_nodes(opt) {
        opt.$div_tabs_nodes.empty();

        opt.$div_tabs_nodes_div = $('<div></div>');

        var formData = new FormData();
        formData.append("action", "nsq:nodes");

        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            if (res.error == 0) {
                opt.$div_tabs_nodes.append(`<h2>NSQd Nodes (${res.producers.length})</h2>`);
                var $table = $(`
        <table class="table">
            <thead>
                <tr>
                    <th>Hostname</th>
                    <th>Broadcast Address</th>
                    <th>TCP Port</th>
                    <th>HTTP Port</th>
                    <th>Version</th>
                    <th>Lookupd Conns.</th>
                    <th>Topics</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
                        `);
                for (var i = 0; i < res.producers.length; i++) {
                    var producer = res.producers[i];

                    var $tr = $(`
                <tr>
                    <td>${producer.hostname}</td>
                    <td class="stats"></td>
                    <td>${producer.tcp_port}</td>
                    <td>${producer.http_port}</td>
                    <td>${producer.version}</td>
                    <td>
                        <a class="conn-count btn btn-default btn-xs btn-warning">1</a>
                        <div style="display: none;">
                            127.0.0.1:4161/127.0.0.1:11059<br>
                        </div>
                    </td>
                    <td>
                        <ul class="topics">
                        </ul>
                    </td>
                </tr>
                                `);

                    var $a = $('<a href="javascript:void(0);">' + producer.broadcast_address + '</a>');
                    $a.data("objdata", {
                        broadcast_address: producer.broadcast_address,
                        http_port: producer.http_port,
                        $div: opt.$div_tabs_nodes_div
                    });

                    $tr.find(".stats").append($a);

                    $a.bind("click", function () {
                        nsq_stats(opt, $(this));
                    })

                    for (var j = 0; j < producer.topics.length; j++) {
                        var topic = producer.topics[j];
                        var $li = $('<li><a href="javascript:void(0);">' + topic + '</a></li>');
                        $li.find("a").data("objdata", {
                            topic: topic,
                            broadcast_address: producer.broadcast_address,
                            $div: opt.$div_tabs_nodes_div
                        });
                        $li.find("a").bind("click", function () {
                            nsq_lookup(opt, $(this));
                        })
                        $tr.find(".topics").append($li);
                    }

                    $table.find("tbody").append($tr);
                }

                opt.$div_tabs_nodes.append($table);
                opt.$div_tabs_nodes.append(opt.$div_tabs_nodes_div);
            }
        })
    }

    function dip_lookup(opt) {
        opt.$div_tabs_lookup.empty();
        opt.$div_tabs_lookup_div = $('<div></div>');

        var formData = new FormData();
        formData.append("action", "nsq:topics");

        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            if (res.error == 0) {

            }
        });
    }

    function nsq_lookup(opt, $a) {
        var objdata = $a.data("objdata");
        objdata.$div.empty();
        objdata.$div.append("<h3>Topic Message Queue：" + objdata.topic + "</h3>");
        var $table = $(`
    <table class="table">
        <thead>
            <tr>
                <th>NSQd Host</th>
                <th>Broadcast Address</th>
                <th>TCP Port</th>
                <th>HTTP Port</th>
                <th>Depth </br>（深度）</th>
                <th>Memory + Disk </br>（内存和磁盘使用）</th>
                <th>Messages </br>（消息数）</th>        
                <th>Channels </br>（通道数）</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
                    `);

        var formData = new FormData();
        formData.append("action", "nsq:lookup");
        formData.append("topic", objdata.topic);
        if (!(objdata.broadcast_address === undefined)) {
            formData.append("broadcast_address", objdata.broadcast_address);
        }

        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            if (res.error == 0) {
                for (var i = 0; i < res.producers.length; i++) {
                    var producer = res.producers[i];


                    var $tr = $(`
            <tr>
                <td>
                    <button>✘</button>
                    ${producer.hostname}
                </td>
                <td class="hostname">           
                </td>
                <td>${producer.tcp_port}</td>
                <td>${producer.http_port}</td>
                <td>${producer.depth}</td>
                <td>${producer.e2e_processing_latency.count} + ${producer.e2e_processing_latency.percentiles === null ? 0 : producer.e2e_processing_latency.percentiles}</td>
                <td>${producer.message_count}</td>
                <td>${producer.channels.length}</td>
            </tr>
                                `);

                    var $a;
                    if (objdata.broadcast_address === undefined) {
                        $a = $('<a href="javascript:void(0);">' + producer.broadcast_address + '</a>');
                        $a.data("objdata", {
                            broadcast_address: producer.broadcast_address,
                            http_port: producer.http_port,
                            $div: objdata.$div
                        });

                        $a.bind("click", function () {
                            nsq_stats(opt, $(this));
                        })
                    } else {
                        $a = producer.broadcast_address;
                    }
                    $tr.find(".hostname").append($a);

                    $table.find("tbody").append($tr);
                }
                objdata.$div.append($table);

                if (objdata.broadcast_address === undefined && res.producers.length > 0) {
                    return;
                }

                var channels = [];
                if (res.producers.length > 0) {
                    channels = res.producers[0].channels;
                }
                console.log("channels", channels);

                var $info = $(`
        <h2>Channel Message Queues</h2>
        <table class="table">
            <thead>
                <tr>
                    <th>Channel</th>
                    <th>Depth</th>
                    <th>Memory + Disk</th>
                    <th>In-Flight</th>
                    <th>Deferred</th>
                    <th>Requeued</th>
                    <th>Timed Out</th>
                    <th>Messages</th>
                    <th>Connections</th>
                </tr>
            </thead>
            <tbody>    
            </tbody>
        </table>`);

                for (var i = 0; i < channels.length; i++) {
                    var channel = channels[i];
                    $info.find("tbody").append(`
                <tr>
                    <th>
                        <a class="link" href="/topics/topic/channel">${channel.channel_name}</a>
                    </th>
                    <td>${channel.depth}</td>
                    <td>${channel.e2e_processing_latency.count} + ${channel.e2e_processing_latency.percentiles === null ? 0 : channel.e2e_processing_latency.percentiles}</td>
                    <td>${channel.in_flight_count}</td>
                    <td>${channel.deferred_count}</td>
                    <td>${channel.requeue_count}</td>
                    <td>${channel.timeout_count}</td>
                    <td>${channel.message_count}</td>
                    <td>${channel.client_count}</td>
                </tr>
                                `);
                }
                objdata.$div.append($info);
            }
        });
    }

    function nsq_stats(opt, $a) {
        var objdata = $a.data("objdata");
        objdata.$div.empty();
        objdata.$div.append(`<h3>nsq:${objdata.broadcast_address}:${objdata.http_port}</h3>`);

        var formData = new FormData();
        formData.append("action", "nsq:stats");
        formData.append("broadcast_address", objdata.broadcast_address);
        formData.append("http_port", objdata.http_port);

        ajaxLoad(opt, formData, function (res) {
            console.log(res);
            if (res.error != 0) {
                $.yqMessager("error", res.info);
                return;
            }

            var $table = $(`
    <table class="table">
        <tbody>
            <tr>
                <td colspan="2"><strong>Topics</strong> </td>
                <td colspan="7"></td>
                <td><strong>0</strong>Messages</td>
                <td><strong>0</strong>Clients</td>
            </tr>
            <tr>
                <td colspan="10">&nbsp</td>
            </tr>
        </tbody>
    </table>
                        `);

            for (var i = 0; i < res.topics.length; i++) {
                var topic = res.topics[i];
                var $tr = $(`
            <tr>
                <th colspan="3">Topic</th>
                <th>Depth</th>
                <th>Memory + Disk</th>
                <th colspan="4"></th>
                <th>Messages</th>
                <th>Channels</th>
            </tr>
            <tr>
                <td colspan="10">&nbsp</td>
            </tr>
            <tr class="info">
                <td colspan="3">
                    <button>✘</button> ${topic.topic_name}  
                </td>
                <td>
                    ${topic.depth}
                </td>
                <td>${topic.e2e_processing_latency.count} + ${topic.e2e_processing_latency.percentiles === null ? 0 : topic.e2e_processing_latency.percentiles}</td>
                <td colspan="4"></td>
                <td>
                    ${topic.message_count}
                </td>
                <td>
                    ${topic.channels.length}    
                </td>
            </tr>`);
                $table.find("tbody").append($tr);

                if (topic.channels.length == 0) {
                    $table.find("tbody").append(`<tr><td colspan="11"><div class="alert alert-warning"><h4>Notice</h4>No channels exist for this topic.</div></td></tr>`);
                } else {
                    $tr = $(`
            <tr>
                <th width="25"></th>
                <th colspan="2">Channel</th>
                <th>Depth</th>
                <th>Memory + Disk</th>
                <th>In-Flight</th>
                <th>Deferred</th>
                <th>Requeued</th>
                <th>Timed Out</th>
                <th>Messages</th>
                <th>Connections</th>
            </tr>
                                    `);
                    $table.find("tbody").append($tr);

                    for (var j = 0; j < topic.channels.length; j++) {
                        var channel = topic.channels[j];
                        $tr = $(`
            <tr class="warning">
                <td></td>
                <td colspan="2">
                    ${channel.channel_name}
                </td>
                <td>
                    ${channel.depth}
                </td>
                <td>${channel.e2e_processing_latency.count} + ${channel.e2e_processing_latency.percentiles === null ? 0 : channel.e2e_processing_latency.percentiles}</td>
                <td>${channel.in_flight_count}</td>
                <td>${channel.deferred_count}</td>
                <td>${channel.requeue_count}</td>
                <td>${channel.timeout_count}</td>
                <td>${channel.message_count}</td>
                <td>${channel.clients.length}</td>
            </tr>
                                    `);
                        $table.find("tbody").append($tr);
                        if (channel.clients.length == 0) {
                            $tr.after(`<tr><td colspan="11"><div class="alert alert-warning"><h4>Notice</h4>No clients connected to this channel.</div></td></tr>`);
                        }
                    }
                }
            }

            objdata.$div.append($table);
        });
    }



    function ajaxLoad(opt, formData, callback) {
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    callback(res);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                callback({
                    error: 1,
                    info: "请求失败",
                });
            }
        });
    }
})(jQuery);
